package com.example.webdownloadserver.base;

import com.example.webdownloadserver.common.TaskConstants;
import com.example.webdownloadserver.constants.TaskCenterConstants;
import com.example.webdownloadserver.core.ITaskProcess;
import com.example.webdownloadserver.core.TaskHandlerUtil;
import com.example.webdownloadserver.service.TaskCenterService;
import com.example.webdownloadserver.vo.TaskCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * <p>
 * 任务封装
 * </p>
 * @title TaskDownloadHandleThread.java
 * @package com.dnkj.download.task.base 
 * @author ying.xiao
 * @version 0.1 2020年12月5日
 */
public class TaskDownloadHandleThread implements Runnable {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private TaskCenterService taskCenterService;
	
	private TaskCenter taskCenter;
	

	public TaskDownloadHandleThread(TaskCenterService taskCenterService,TaskCenter taskCenter) {
		this.taskCenterService = taskCenterService;
		this.taskCenter = taskCenter;
	}

	public void run() {
		boolean flag = false;
		try {
			if (TaskConstants.TASK_TYPE_D.equals(taskCenter.getTaskType())) {
				download(taskCenter);
			}
			flag = true;
		}catch (TaskJobException e) {
			taskCenter.setTaskStatus(TaskCenterConstants.TASK_STATUS_FAIL);
			taskCenter.setTaskCleanFlag(TaskCenterConstants.TASK_CLEAN_FLAG_CAN);
			taskCenter.setTaskRemark(e.getMessage());
		}catch (Exception e) {
			logger.error("处理下载任务异常", e);
			taskCenter.setTaskStatus(TaskCenterConstants.TASK_STATUS_FAIL);
			taskCenter.setTaskCleanFlag(TaskCenterConstants.TASK_CLEAN_FLAG_CAN);
			taskCenter.setTaskRemark("找不到下载任务处理类");
		}
		if(!flag) {
			taskCenterService.update(taskCenter);
		}
	}

	public void download(TaskCenter taskCenter) {
		ITaskProcess iface = (ITaskProcess) TaskHandlerUtil.downloadHandlerBeanMap.get(taskCenter.getTaskHandler());
		iface.handler(taskCenter);
	}

}